<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="工程量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packageGridId">
              <a-select
                show-search
                optionFilterProp="children"
                v-model="model.packageGridId"
                placeholder="请选择"
                @change="handleChange"
              >
                <a-select-option :value="item.gridCode" v-for="item in gridDynamicsLengthIdList" :key="item.id">{{
                  item.gridName
                }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24" v-if="type">
            <a-form-model-item label="工程量值" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packageGridValue">
              <div v-if="title == 'create'">
                <a-select
                  v-if="type == 'SELECT'"
                  show-search
                  optionFilterProp="children"
                  v-model="model.packageGridValue"
                  placeholder="请选择"
                >
                  <a-select-option :value="item.enumValue" v-for="item in packageGridValueList" :key="item.id">{{
                    item.enumName
                  }}</a-select-option>
                </a-select>

                <div v-if="type == 'INPUT' || type == 'BYTE_STREAM'" id="telWrap">
                  <div>
                    <span :key="index" v-for="(i, index) in length">
                      <a-input
                        :maxLength="2"
                        style="width: 50px; margin-right: 10px"
                        v-model="model.Values[index]"
                        @change="
                          (val) => {
                            handleInput(val, model.Values)
                          }
                        "
                      ></a-input>
                    </span>
                    <div style="color: red" v-if="falseFlag">请输入两位16进制数</div>
                  </div>
                </div>
              </div>
              <div v-if="title == 'update'">
                <a-select
                  v-if="type == 'SELECT'"
                  show-search
                  optionFilterProp="children"
                  v-model="model.packageGridValue"
                  placeholder="请选择"
                >
                  <a-select-option :value="item.enumValue" v-for="item in packageGridValueList" :key="item.id">{{
                    item.enumName
                  }}</a-select-option>
                </a-select>
                <a-input v-if="type == 'INPUT' || type == 'BYTE_STREAM'" v-model="model.packageGridValue"></a-input>
              </div>
              <!-- <a-input
                v-if="(type == 'INPUT' || type == 'BYTE_STREAM') && title == 'update'"
                v-model="model.packageGridValue"
              ></a-input> -->
              <!-- <a-input v-model="model.packageGridValue" placeholder="请输入工程量值" v-else></a-input> -->
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="24" v-if="type == 'SELECT'">
            <a-form-model-item
              label="工程量值枚举"
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              prop="packageGridValue"
            >
              <a-select v-model="model.packageGridValue" placeholder="请选择">
                <a-select-option :value="item.enumValue" v-for="item in packageGridValueList" :key="item.id">{{
                  item.enumName
                }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col> -->
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'

export default {
  name: 'NmcPackageGridValueForm',
  components: {},
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  data() {
    const validatorOx = (rule, value, callback) => {
      console.log(value)
      if (/^[A-Fa-f0-9]{2}$/.test(value) || value == undefined) {
        callback()
      } else {
        callback(new Error('请输入3位十六进制数'))
      }
    }
    return {
      title: '',
      falseFlag: false,
      model: { Values: [] },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        Ox: [{ required: true, message: '请输入新闻标题', trigger: 'blur' }, { validator: validatorOx }],
      },
      url: {
        add: '/grid/nmcPackageGridValue/add',
        edit: '/grid/nmcPackageGridValue/edit',
        queryById: '/grid/nmcPackageGridValue/queryById',
        PackageGridList: '/grid/nmcPackageGrid/list',
        packageGridValueList: '/grid/nmcPackageGridEnum/list',
      },
      gridDynamicsLengthIdList: [],
      packageGridValueList: [],
      type: null,
      enumtype: null,
      length: 2,
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
    // document.addEventListener('keyup', this.tabForward) //光标自动切换
  },
  methods: {
    tabForward(event) {
      var target = event.target
      if (target.value.length == target.maxLength) {
        // 注意不是maxlength
        var elements = document.getElementById('telWrap').getElementsByTagName('input')
        for (let i = 0; i < elements.length; i++) {
          if (elements[i] == target) {
            if (elements[i + 1] && !this.falseFlag) {
              elements[i + 1].focus()
            }
            return // 退出当前函数
          }
        }
      }
    },
    handleInput(e, record) {
      console.log(record)
      this.falseFlag = false
      let val = e.target.value
      let reg = /^[A-Fa-f0-9]{2}$/
      if (!reg.test(val)) {
        this.falseFlag = true
        return false
      }
      if (record.length > 0) {
        record.forEach((e) => {
          if (!reg.test(e)) {
            this.falseFlag = true
            return false
          }
        })
      }
    },
    handleChange(val) {
      let temp
      if (this.gridDynamicsLengthIdList.length > 0) {
        temp = this.gridDynamicsLengthIdList.find((i) => i.gridCode == val)
      }
      if (temp) {
        this.type = temp.gridInputType
        this.enumtype = temp.gridEnumsTypeId
        // this.enumtype = temp.gridEnumsId
        if (this.type == 'SELECT') {
          getAction(`${this.url.packageGridValueList}?enumTypeId=${temp.gridEnumsTypeId}`, {}).then((res) => {
            this.packageGridValueList = [...res.result.records]
          })
        } else if (this.type == 'INPUT') {
          this.length = temp.gridStaticLength

          // console.log(this.length, 'this.length')
        }
      }
    },
    getList() {
      //工程量列表
      getAction(this.url.PackageGridList, { pageSize: -1 }).then((res) => {
        this.gridDynamicsLengthIdList = [...res.result.records]
        let temp = this.gridDynamicsLengthIdList.find((i) => i.id == this.model.packageGridId)
        this.type = temp.gridInputType
        // this.enumtype = temp.gridEnumsId
        this.enumtype = temp.gridEnumsTypeId

        if (this.type == 'SELECT') {
          getAction(`${this.url.packageGridValueList}?enumTypeId=${temp.gridEnumsTypeId}`, {}).then((res) => {
            this.packageGridValueList = [...res.result.records]
            // console.log(this.packageGridValueList)
          })
        }
      })
    },
    add() {
      this.edit(this.modelDefault, 1)
    },
    edit(record, val) {
      if (!val) {
        this.title = 'update'
      } else {
        this.title = 'create'
      }
      console.log(record)
      this.model = Object.assign({}, record)
      this.getList()

      this.handleChange(this.model.packageGridId)
      this.visible = true
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid && !that.falseFlag) {
          if (that.type == 'INPUT') {
            that.model.packageGridValue = that.model.Values.join('').toUpperCase()
          }
          // console.log(that.model)
          // return
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.model.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          delete that.model.Values
          httpAction(httpurl, this.model, method)
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
        }
      })
    },
  },
}
</script>
